package com.chendechao.a2207a_ivideo

import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.os.CountDownTimer
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.chendechao.model_home.HomeActivity
import com.example.model_user.login.LoginActivity
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    private lateinit var sharedPreferences: SharedPreferences

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        val countdownText = findViewById<TextView>(R.id.countdown_text)

        // 初始化 SharedPreferences
        sharedPreferences = getSharedPreferences("AppPrefs", MODE_PRIVATE)

        // 检查是否已经同意过协议
        if (!sharedPreferences.getBoolean("hasAgreedToTerms", false)) {
            // 添加弹窗逻辑
            val builder = AlertDialog.Builder(this)
            builder.setTitle("用户协议与隐私政策")
            builder.setMessage("请阅读并同意以下协议：\n\n1. 用户协议\n2. 隐私协议")
            builder.setPositiveButton("同意") { _, _ ->
                // 用户同意后启动倒计时
                sharedPreferences.edit().putBoolean("hasAgreedToTerms", true).apply()
                object : CountDownTimer(5000, 1000) {
                    override fun onTick(millisUntilFinished: Long) {
                        countdownText?.text = "倒计时${millisUntilFinished / 1000}S"
                    }

                    override fun onFinish() {
                        val intent = Intent(this@MainActivity, HomeActivity::class.java)
                        startActivity(intent)
                        finish() // 如果希望关闭当前的 MainActivity，可添加这行代码
                    }
                }.start()
            }
            builder.setNegativeButton("不同意") { _, _ ->
                // 用户不同意则退出应用
                finishAffinity()
            }
            builder.setCancelable(false) // 禁止用户通过返回键关闭弹窗
            builder.show()
        } else {
            // 如果已经同意过协议，直接启动倒计时
            object : CountDownTimer(5000, 1000) {
                override fun onTick(millisUntilFinished: Long) {
                    countdownText?.text = "倒计时${millisUntilFinished / 1000}S"
                }

                override fun onFinish() {
                    val intent = Intent(this@MainActivity, HomeActivity::class.java)
                    startActivity(intent)
                    finish() // 如果希望关闭当前的 MainActivity，可添加这行代码
                }
            }.start()
        }
    }
}